package com.clb.studyproject.weights

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import kotlin.math.abs
import kotlin.properties.Delegates

class SignatureView : View {

    constructor(context: Context) : super(context) {
        init(context)
    }

    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
        init(context, attributeSet)
    }

    private var paint: Paint = Paint()

    //笔的颜色
    private var drawColor = Color.BLACK

    //笔的粗细
    private val drawWidth = 5F

    //每次绘制的路径
    private lateinit var path: Path

    //每次落笔的横坐标
    private var downX by Delegates.notNull<Float>()

    //每次落笔的纵坐标
    private var downY by Delegates.notNull<Float>()

    //最小划线距离
    private var minPath = 0.1

    private fun init(context: Context, attributeSet: AttributeSet? = null) {
        paint.color = drawColor
        paint.strokeWidth = drawWidth
        paint.style = Paint.Style.STROKE
        paint.isAntiAlias = true

        path = Path()
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event != null) {
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    downX = event.x
                    downY = event.y
                    path.moveTo(downX, downY)
                }
                MotionEvent.ACTION_MOVE -> {
                    val difX = event.x - downX
                    val difY = event.y - downY

                    if (abs(difX) > minPath || abs(difY) > minPath) {
                        //画出该段距离的曲线，并将dif重置为0，重新计算差值
                        path.quadTo((downX + event.x) / 2, (downY + event.y) / 2, event.x, event.y)
                        downX = event.x
                        downY = event.y
                    }
                }
                else -> {
                }
            }
        }
        invalidate()
        return true
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.drawPath(path, paint)
    }

    fun getBitmap(): Bitmap? {
        val createBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(createBitmap)
        this.draw(canvas)
        canvas.save()
        return createBitmap
    }
}